package club.easin.interceptor;

import club.easin.MYException;
import club.easin.common.UserBl;
import club.easin.config.ConfigEunum;
import club.easin.enums.Exenum;
import club.easin.pow.dto.UserSession;
import club.easin.utils.ReturnUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthoInterceptor{

    @Autowired
    UserBl userBl;

    @Pointcut(value = ConfigEunum.authpioncut)
    public void autho(){

    }

    @Around("autho()")
    public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result=null;
        try {
            HttpServletRequest request= ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            Object met[]=joinPoint.getArgs();
            UserSession userSession=null;
            for (int i=0;i<met.length;i++) {
                if (met[i].getClass().equals(UserSession.class)) {
                    userSession=userBl.verifyToken(request);
                    met[i]=userSession;
                    System.out.println(met[i]);
                }
            }
            result=joinPoint.proceed(met);
        }catch (MYException e){
            e.printStackTrace();
            result= ReturnUtils.returnError(e.getMessage());
        }
        catch (Throwable e){
            e.printStackTrace();
            result=ReturnUtils.returnError(Exenum.SYS_ERROE);
        }
        return result;

    }
}
